package com.robot.admin.service;

import com.robot.admin.dao.AdminDao;
import com.robot.admin.pojo.Admin;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * admin服务层
 *
 * @author wuyunbin
 */
@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每天最多发送短信次数
     */
    @Value("${sys.sendSmsCount}")
    private int sysSendSmsCount;

    @Value("${sys.scene}")
    private String sceneInYml;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Admin> findAll() {
        return adminDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Admin> findSearch(Map whereMap, int page, int size) {
        Specification<Admin> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return adminDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Admin> findSearch(Map whereMap) {
        Specification<Admin> specification = createSpecification(whereMap);
        return adminDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Admin findById(String id) {
        return adminDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param admin
     */
    public void add(Admin admin) {
        //雪花分布式ID生成器
        admin.setId(idWorker.nextId() + "");
        adminDao.save(admin);
    }

    /**
     * 修改
     *
     * @param admin
     */
    public void update(Admin admin) {
        adminDao.save(admin);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        adminDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Admin> createSpecification(Map searchMap) {
        return new Specification<Admin>() {
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 管理员id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 手机
                String phone = "phone";
                if (searchMap.get(phone) != null && !"".equals(searchMap.get(phone))) {
                    predicateList.add(cb.like(root.get(phone).as(String.class), "%" + (String) searchMap.get(phone) + "%"));
                }
                // 密码
                String password = "password";
                if (searchMap.get(password) != null && !"".equals(searchMap.get(password))) {
                    predicateList.add(cb.like(root.get(password).as(String.class), "%" + (String) searchMap.get(password) + "%"));
                }
                // 昵称
                String nickname = "nickname";
                if (searchMap.get(nickname) != null && !"".equals(searchMap.get(nickname))) {
                    predicateList.add(cb.like(root.get(nickname).as(String.class), "%" + (String) searchMap.get(nickname) + "%"));
                }
                // 角色id
                String roleId = "roleId";
                if (searchMap.get(roleId) != null && !"".equals(searchMap.get(roleId))) {
                    predicateList.add(cb.like(root.get(roleId).as(String.class), "%" + (String) searchMap.get(roleId) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(Date.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @param flag  场景值 登录="login" 修改手机号="updatePhone",修改密码="updatePassword"
     */
    public boolean sendSms(String phone, String flag) {
        //先检查这个场景下的短信条数
        int count = counter(flag, phone);
        if (count >= sysSendSmsCount) {
            //超过了限制
            logger.info("sendSms:发送次数超过限制");
            return false;
        }
        return send(flag, phone, count);

    }

    /**
     * 短信发送
     *
     * @param flag  场景值
     * @param phone 手机号
     * @param count 计数
     * @return 是否发送成功
     */
    private boolean send(String flag, String phone, int count) {
        //拼接存验证码的RedisKey
        String checkCodeRedisKey = getCheckCodeRedisKey(flag, phone);
        //生成4位随机数
        String checkCode = RandomStringUtils.randomNumeric(4);
        //随机数存到Redis设置过期时间为10分钟
        redisTemplate.opsForValue().set(checkCodeRedisKey, checkCode, 10, TimeUnit.MINUTES);
        logger.info("send:phone=" + phone + " RedisKey=" + checkCodeRedisKey + " CheckCode=" + checkCode);
        //存一个到rabbitMq
        HashMap<String, String> map = new HashMap<>(2);
        map.put("phone", phone);
        map.put("checkCode", checkCode);
        rabbitTemplate.convertAndSend("sms", map);
        //拼接计数器的counterRedisKey
        String counterRedisKey = getCounterRedisKey(flag, phone);
        redisTemplate.opsForValue().set(counterRedisKey, ++count);

        return true;
    }

    /**
     * 是否存在这个场景值
     *
     * @param flag 要判断的场景
     * @return true 存在 false 不存在
     */
    public boolean isCorrectScene(String flag) {
        return sceneInYml.contains(flag);
    }

    /**
     * 短信计数器
     *
     * @param flag  场景
     * @param phone 手机号
     * @return 已发送的短信条数
     */
    private int counter(String flag, String phone) {
        //拼接counterRedisKey
        String counterRedisKey = getCounterRedisKey(flag, phone);

        if (!redisTemplate.hasKey(counterRedisKey)) {
            redisTemplate.opsForValue().set(counterRedisKey, 0, 1, TimeUnit.DAYS);
            return 0;
        }
        Object obj = redisTemplate.opsForValue().get(counterRedisKey);
        int count = (int) obj;
        return count;

    }

    /**
     * 检查Redis里面的验证码是不是过期
     *
     * @param flag  场景
     * @param phone 手机号
     * @return true 不过期 false 已过期
     */
    public boolean isCheckCodeExpire(String flag, String phone) {
        //拼接checkCodeRedisKey
        String checkCodeRedisKey = getCheckCodeRedisKey(flag, phone);
        if (!redisTemplate.hasKey(checkCodeRedisKey)) {
            return false;
        }
        return redisTemplate.getExpire(checkCodeRedisKey) > 0;
    }

    /**
     * 检查输入的验证码是不是正确
     *
     * @param flag      场景
     * @param phone     手机号
     * @param checkCode 验证码
     * @return true 正确 false 不正确
     */
    public boolean isCorrectCheckCode(String flag, String phone, String checkCode) {
        //拼接checkCodeRedisKey
        String checkCodeRedisKey = getCheckCodeRedisKey(flag, phone);
        if (!redisTemplate.hasKey(checkCodeRedisKey)) {
            return false;
        }
        String checkCodeInRedis = redisTemplate.opsForValue().get(checkCodeRedisKey).toString();

        return checkCodeInRedis.equals(checkCode);
    }

    /**
     * 删除验证码的key和计数器
     *
     * @param flag  场景
     * @param phone 手机号
     */
    public void deleteCheckCode(String flag, String phone) {
        //拼接场景RedisKey
        redisTemplate.delete(getCheckCodeRedisKey(flag, phone));
        //拼接计数器RedisKey
        redisTemplate.delete(getCounterRedisKey(flag, phone));
    }

    /**
     * 获取验证码的key
     *
     * @param flag  场景
     * @param phone 手机号
     * @return 验证码的key
     */
    private String getCheckCodeRedisKey(String flag, String phone) {
        return "admin" + flag + phone;
    }

    /**
     * 获取验证码计数器的key
     *
     * @param flag  场景
     * @param phone 手机号
     * @return 验证码计数器的key
     */
    private String getCounterRedisKey(String flag, String phone) {
        return "admin" + flag + phone + "counter";
    }

    /**
     * 通过手机号获取一个管理员
     *
     * @param phone 手机号
     * @return Admin
     */
    public Admin findAdminByPhone(String phone) {
        return adminDao.findAdminByPhone(phone);
    }

}
